<?php
	mysql_connect("localhost", "root", "%Tg34fv1")or die("cannot connect"); 
	mysql_select_db("wordWaffle")or die("cannot select DB");
	$myKey = mysql_real_escape_string(stripslashes($_GET['sesskey']));
	$gameID = mysql_real_escape_string(stripslashes($_GET['gameID']));
	//validate sesskey
	$count=mysql_num_rows(mysql_query("SELECT * FROM players WHERE sesskey=$myKey"));
	if ($count==0) //unrecognized session key!
	{
		echo "Intruder alert!";
		return;
	}
	
	//validate gameID
	$results = mysql_query("SELECT * FROM gameStatus WHERE gameID=$gameID");
	if ($row = mysql_fetch_assoc($results)) //unrecognized gameID!
	{
		if ($row['status'] != 0)
		{
			echo "This game is already started.";
			return;
		}
	}
	else
	{
		echo "Game ID does not exist!";
		return;
	}
	
	mysql_query("UPDATE players SET readyToPlay = 2 WHERE readyToPlay = 1");
	mysql_query('TRUNCATE TABLE lettersGuessed'); //clear letters
	mysql_query('TRUNCATE TABLE waffle');	
	mysql_query('TRUNCATE TABLE scores');
	mysql_query('TRUNCATE TABLE allWords');
	$playerList=mysql_query("SELECT * FROM players WHERE readyToPlay = 2");	
	$playerCount=mysql_num_rows($playerList);
	for ($i=1;$i<=25;$i++)
	{
		if (!($row = mysql_fetch_assoc($playerList)))
		{ //back to the beginning
			mysql_data_seek($playerList, 0);
			$row = mysql_fetch_assoc($playerList);
		}
		mysql_query("INSERT INTO lettersGuessed (turnNumber,sesskey) VALUES ('$i','" . $row['sesskey'] . "')");
	}
	mysql_query("UPDATE gameStatus SET status = 1, playerCount = $playerCount WHERE gameID = $gameID");

?>